<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1 style="text-align: center;">登陆</h1>
  <div style="display: flex;justify-content: center;align-items: center;">
    <form>
      {% csrf_token%}
      <div>
        <label for="username">
          用户名:
        </label>
        <input type="text" id='username'>
      </div>
      <div>
        <label for="pwd">
          密码:
        </label>
        <input type="password" id="pwd">
      </div>
      <div style='display: flex;'>
        <label for="pwd">
          验证码:
        </label>
        <div>
          <input id="validcode" type="text">
          <img id='valid_code' src="/valid_code/" alt="">
        </div>
      </div>
      <div>
     
      </div>
    </form>
     <button id='sub'>提交</button> <span id='error' style='color:red'></span>
  </div>
</body>
<script>
  let xhr = new XMLHttpRequest()
  let validBtn = document.getElementById('valid_code');
  /*
    刷新验证码
  */
  validBtn.onclick = function() {
    this.src += '?g'
  }
  let submitBtn = document.getElementById('sub')
  submitBtn.onclick = function() {
    let data = {
      validcode: document.getElementById('validcode').value,
      password: document.getElementById('pwd').value,
      username: document.getElementById('username').value,
      csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value
    }
    let param = []
    for ([key, value] of Object.entries(data)){
      param.push(`${key}=${value}`)
    }
   
    xhr.open('post','/login/', true)
    // django中的request.POST只能取到Content-Type(请求头)为application/x-www-form-urlencoded(form表单默认格式)的数据，如果请求头为application/json(json格式)，multipart/form-data(文件)等格式无法取到，只有在request.body里面能取到原生的数据。当发送过来的是JSON数据是，request.POST取到的数据是空的，这时只有用request.body取，再反序列化才能使用。
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    xhr.send(param.join('&'))
    xhr.onreadystatechange = function(){
      if(xhr.readyState===4&&xhr.status===200){
        let data = JSON.parse(xhr.response)
        if(data.user){
          location.href = '/index/'
        }else{
          document.getElementById('error').innerText = data.msg
        }
      }
    }

    
  }
</script>
</html>